package com.example.demo.controller;

import com.example.demo.mapper.RecommendMapper;
import com.example.demo.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/recommend")
public class RecommendController {

    @Autowired
    private RecommendMapper recommendMapper;

    // 原有接口：通过用户ID查询推荐商品（返回 itemId）
    @GetMapping("/user/{uid}")
    public List<RecommendedItem> getRecommendationsByUser(@PathVariable String uid) {
        return recommendMapper.getTop3Recommendations(uid);
    }

    // 新增接口：通过用户名查询推荐商品（返回 gname）
    @GetMapping("/user/name")
    public List<RecommendedItemWithGname> getRecommendationsByUserName(@RequestParam String name) {
        String uid = recommendMapper.getUidByName(name);
        if (uid == null) {
            throw new RuntimeException("未找到该用户");
        }
        return recommendMapper.getTop3RecommendationsWithGname(uid);
    }

    // 原有接口：通过商品ID查询相似商品（返回 itemId）
    @GetMapping("/item/{itemId}")
    public List<SimilarItem> getSimilarItems(@PathVariable String itemId) {
        return recommendMapper.getTop3SimilarItems(itemId);
    }

    @GetMapping("/user/by-gname")
    public List<RecommendedUser> getTop3UsersByGname(@RequestParam String gname) {
        String gid = recommendMapper.getGidByGname(gname);
        if (gid == null) throw new RuntimeException("未找到该商品");
        return recommendMapper.getTop3UsersByGid(gid);
    }

    // 新增接口：通过商品名称查询相似商品（返回 gname）
    @GetMapping("/item/gname")
    public List<SimilarItemWithGname> getSimilarItemsByGname(@RequestParam String gname) {
        String itemId = recommendMapper.getGidByGname(gname);
        if (itemId == null) {
            throw new RuntimeException("未找到该商品");
        }
        return recommendMapper.getTop3SimilarItemsWithGname(itemId);
    }

    //实时接口
    @GetMapping("/inout/latest")
    public List<InOutData> getLatestInout() {
        return recommendMapper.getLatestInout();
    }

    @GetMapping("/monitor/data")
    public Map<String, Object> getRealtimeMonitorData() {
        Map<String, Object> result = new HashMap<>();

        List<CategoryCount> categories = recommendMapper.getCategoryCounts();
        List<ProductInOut> inOutList = recommendMapper.getProductInOutCounts();

        result.put("categories", categories);
        result.put("inOutList", inOutList);

        return result;
    }

}
